import asyncio
from PyQt6.QtCore import QThread, pyqtSignal
from PyQt6.QtWidgets import QMessageBox, QApplication
import crsky
from spider import Ui_spider_main


class Thread(QThread):
    finished = pyqtSignal(str)

    def __init__(self, window, params: dict):
        super().__init__()
        self.window = window
        self.params = params

    def run(self):
        try:
            asyncio.run(crsky.main(self.window, self.params))
            self.finished.emit("采集完成！")
        except Exception as e:
            self.finished.emit("采集出现错误！:" + str(e))


def start_task(window: Ui_spider_main):
    params = {
        "url": window.site_path.text(),
        "site_path": window.site_path.text(),
        "down_path": window.down_path.text(),
        "page_number": window.page_number.text(),
        "csv_name": window.csv_name.text(),
        "category": window.category.text(),
        "image_path": window.image_path.text(),
    }
    window.gather_thread = Thread(window, params)
    window.gather_thread.finished.connect(lambda msg: gather_finished(msg))
    window.gather_thread.start()


def gather_finished(msg: str):
    QMessageBox.information(None, "提示", msg)
